//
//  NetworkManager.m
//  GodCoin
//
//  Created by Xiaohan on 2018/6/5.
//  Copyright © 2018年 xiaohan. All rights reserved.
//

#import "NetworkManager.h"
#import "TimeHelper.h"
#import "XKeyChainUDID.h"
@implementation NetworkManager
+ (__kindof NSURLSessionTask *)GET:(NSString *)URL
                        parameters:(id)parameters
                     responseCache:(PPHttpRequestCache)responseCache
                           success:(PPHttpRequestSuccess)success
                           failure:(PPHttpRequestFailed)failure {
    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super GET:URL parameters:newParameters responseCache:responseCache success:success failure:failure];
}
#pragma mark - POST请求
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL
                         parameters:(id)parameters
                      responseCache:(PPHttpRequestCache)responseCache
                            success:(PPHttpRequestSuccess)success
                            failure:(PPHttpRequestFailed)failure {

    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super POST:URL parameters:newParameters responseCache:responseCache success:success failure:failure];
}
#pragma mark - PUT请求缓存
+ (__kindof NSURLSessionTask *)PUT:(NSString *)URL parameters:(id)parameters success:(PPHttpRequestSuccess)success failure:(PPHttpRequestFailed)failure{
    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super PUT:URL parameters:newParameters responseCache:nil  success:success failure:failure];
}
+ (__kindof NSURLSessionTask *)DELETE:(NSString *)URL
                           parameters:(id)parameters
                              success:(PPHttpRequestSuccess)success
                              failure:(PPHttpRequestFailed)failure{
    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super DELETE:URL parameters:newParameters responseCache:nil  success:success failure:failure];
}

+ (__kindof NSURLSessionTask*)uploadImagesWithURL:(NSString *)URL
                                       parameters:(id)parameters
                                             name:(NSString *)name
                                           images:(NSArray<UIImage *> *)images
                                        fileNames:(NSArray<NSString *> *)fileNames
                                       imageScale:(CGFloat)imageScale
                                        imageType:(NSString *)imageType
                                         progress:(PPHttpProgress)progress
                                          success:(PPHttpRequestSuccess)success
                                          failure:(PPHttpRequestFailed)failure{
    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super uploadImagesWithURL:URL parameters:newParameters name:name images:images fileNames:fileNames imageScale:imageScale imageType:imageType progress:progress success:success failure:failure];
}

+ (__kindof NSURLSessionTask*)uploadFileWithURL:(NSString *)URL
                             parameters:(id)parameters
                                   name:(NSString *)name
                               filePath:(NSString *)filePath
                               progress:(PPHttpProgress)progress
                                success:(PPHttpRequestSuccess)success
                                failure:(PPHttpRequestFailed)failure{

    if (kUserManager.isLogined && kCurUser.jwt_token.length) {
        [self setValue:kCurUser.jwt_token forHTTPHeaderField:@"authorization"];
    }
    NSDictionary *newParameters = [self creatSignWithParameter:parameters];
    return [super uploadFileWithURL:URL parameters:newParameters name:name filePath:filePath progress:progress success:success
            failure:failure];
}
///下载二进制流
+ (__kindof NSURLSessionTask*)downloadFileStreamWithHTTPMethod:(NSString*)HTTPMethod
                                                           Url:(NSString*)urlStr
                                                       success:(PPHttpRequestSuccess)success
{
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = HTTPMethod;
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                !success?:success(nil);
            }else
            {
                !success?:success(data);
            }
        });
       
    }];
    [task resume];
    return task;
}

+ (NSDictionary *)creatSignWithParameter:(NSDictionary*)param{
  
    NSMutableDictionary*mutableParam = param.mutableCopy;
    NSString *noncestr = [RegularExp getRandomStringWithNum:32];
    NSString *timestamp= [TimeHelper getCurrentTimestamp];
    mutableParam[@"noncestr"] = noncestr;
    mutableParam[@"timestamp"] = timestamp;
    mutableParam[@"did"] = [XKeyChainUDID getDeviceIDInKeychain];
    NSArray *keyArray = [mutableParam allKeys];
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
        }];
    NSMutableArray*parArr = @[].mutableCopy;
    for (NSString *sortString in sortArray) {
        [parArr addObject:[NSString stringWithFormat:@"%@=%@",sortString,mutableParam[sortString]]];
    }
    NSString *keyStr = [NSString stringWithFormat:@"key=%@",kSignKey];
    [parArr addObject:keyStr];
    NSString *signStr = [parArr componentsJoinedByString:@"&"];
    NSString *md5Sign = [[signStr md5String] uppercaseString];
    mutableParam[@"sign"] = md5Sign;
    return mutableParam.copy;
}

+ (NSString *)creatGETUrl:(NSString*)urlStr parameter:(NSDictionary*)param{
    NSMutableString *URL = [NSMutableString stringWithFormat:@"%@",urlStr];
    //获取字典的所有keys
    NSArray * keys = [param allKeys];
    
    //拼接字符串
    for (int j = 0; j < keys.count; j ++){
        NSString *string;
        if (j == 0){
            //拼接时加？
            string = [NSString stringWithFormat:@"?%@=%@", keys[j], param[keys[j]]];
            
        }else{
            //拼接时加&
            string = [NSString stringWithFormat:@"&%@=%@", keys[j], param[keys[j]]];
        }
        //拼接字符串
        [URL appendString:string];
    }
    return URL;
}
@end
